package com.lcn.comm.framework.netty;

import com.lcn.comm.constant.Constants;
import com.lcn.comm.domain.TxRequest;
import com.weibo.api.motan.rpc.URL;
import com.weibo.api.motan.transport.netty4.NettyClient;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @create: 2017－12－24 上午10:05
 */
public class NettyClientManager {

    private static NettyClientManager instance = null;

    private static Map<String, NettyClient> nettyClientMap = new ConcurrentHashMap<String, NettyClient>();

    Map<String, String> parameters = new HashMap<String, String>();

    private NettyClientManager() {
        parameters.put("requestTimeout", "50000");
    }

    public static NettyClientManager getInstance() {
        if (instance == null) {
            synchronized (NettyClientManager.class) {
                if (instance == null) {
                    instance = new NettyClientManager();
                }
            }
        }
        return instance;
    }

    /**
     * 获取netty通信客户端
     *
     * @param txRequest
     * @return
     */
    public NettyClient getNettyClient(TxRequest txRequest) {
        String md5Key = getMd5Key(txRequest);
        NettyClient nettyClient1 = nettyClientMap.get(md5Key);
        if (nettyClient1 == null) {
            synchronized (md5Key.intern()) {
                NettyClient nettyClient = nettyClientMap.get(md5Key);
                if (nettyClient == null) {
                    nettyClient = initNettyClient(txRequest);
                }
                return nettyClient;
            }
        }
        return nettyClient1;
    }

    /**
     * 初始化netty客户端
     *
     * @param txRequest
     */
    private NettyClient initNettyClient(TxRequest txRequest) {
        NettyClient nettyClient = new NettyClient(getUrl(txRequest));
        nettyClient.open();
        nettyClientMap.put(getMd5Key(txRequest), nettyClient);
        return nettyClient;
    }

    /**
     * 组装通信url
     *
     * @param txRequest
     * @return
     */
    private URL getUrl(TxRequest txRequest) {
        return new URL("motan", txRequest.getIpAddress(), txRequest.getPort(), Constants.callBackInterfaceName, parameters);
    }

    private String getMd5Key(TxRequest txRequest) {
        return txRequest.getIpAddress() + txRequest.getPort() + Constants.callBackInterfaceName;
    }
}
